Skip to content

Drop ESCPOS_NET from CrossEscPos.Transports - #27

Open
danielmeza wants to merge 2 commits into
mainfrom
fix/drop-escpos-net
Open

danielmeza wants to merge 2 commits into
mainfrom
fix/drop-escpos-net

Conversation

@danielmeza

@danielmeza danielmeza commented Oct 8, 2026 •

Copy link
Copy Markdown
Owner

Why

ESCPOS_NET 3.0.0 is the library's last release (2022-08-18); upstream's last commit is 2024-09-18.
CrossEscPos.Transports depended on it for exactly one type, and paid for it with the package's
whole dependency floor.

UsbPrinter was the only one of the four transports deriving from it. Its three siblings use this
repository's own seam:

File Derives from
src/CrossEscPos.Transports/UsbPrinter.cs ESCPOS_NET.BasePrinter
src/CrossEscPos.Transports/NetClient.cs IPrinterResponder
src/CrossEscPos.Transports/SerialServer.cs IPrinterResponder
src/CrossEscPos.Transports/NetServer.cs β€”

And it used almost none of BasePrinter: it built its own BinaryWriter/BinaryReader over its own
UsbStream and overrode OverridableDispose(). Everything else in the file was UsbStream, which is
plain System.IO.Stream.

What BasePrinter actually did with the status bytes

Measured by decompiling the exact DLL this repository restores
(~/.nuget/packages/escpos_net/3.0.0/lib/netstandard2.0/ESCPOS_NET.dll, via ilspycmd), not from
upstream source:

  1. ReadLongRunningTask() β€” a background loop: await Task.Delay(100), then
    Reader.BaseStream.ReadByte(). One byte per 100 ms. Each byte went into a
    ConcurrentQueue<byte> and then called DataAvailable().
  2. DataAvailable() β€” if (ReadBuffer.Count() % 4 != 0) return; then dequeue exactly 4 bytes.
    Since it ran once per byte, this degenerates to plain 4-byte grouping.
  3. TryUpdatePrinterStatus(byte[4]) β€” validated byte 0 (bit 4 set; bits 0, 1, 7 clear), built a
    12-property PrinterStatusEventArgs, and raised StatusChanged. Byte 3 was never read. If
    validation failed, Status was left stale but the event still fired β€” the if (StatusChanged != null) block sits outside the validation if.

So UsbPrinter did already read the channel itself (UsbStream.Read, bulk-IN, its own timeout and
buffer); BasePrinter contributed the pump cadence, the 4-byte framing, and the bit decode.

Someone consumes it, so the behaviour is preserved

The brief offered three exits. Exit 2 is the one the measurement forces:
src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs held the printer as BasePrinter?,
subscribed StatusChanged, and mapped PrinterStatusEventArgs onto MonitorStatus β€” which drives
the Monitor's Printer / Paper / Cover / Cash drawer / Error indicators. Deleting the parse would have
silently blanked the desktop USB status panel.

It is preserved with code already in the repository rather than a new parser:
MonitorStatus.FromAutoStatusBack β€” the browser head's decode of the same 4-byte block
(WebMonitorClient.OnStatusBytes) β€” was already a second, independent implementation of
TryUpdatePrinterStatus. The two are now one.

  • AutoStatusBackReader (new, in CrossEscPos.Core) frames the channel into 4-byte blocks and
    decodes one. It sits next to StatusByteBuilder.AutoStatusBack, whose exact inverse it is, and a
    test asserts that inverse over all 144 PrinterState combinations.
  • MonitorStatus.FromAutoStatusBack now delegates to it, so the desktop and browser heads report
    a given block identically β€” they did not before.
  • StreamPrinter (new, in CrossEscPos.Transports) is the host side of a printer conversation
    over any Stream: IPrinterResponder.Send out, raw blocks back on StatusFrameReceived.
    UsbPrinter derives from it and supplies the UsbStream. Transports keeps no bit semantics, the
    same as its three siblings.

Two ESCPOS_NET details kept on purpose

Both are invisible against this emulator and reachable on real hardware, so dropping them would have
been a silent regression:

  • The fixed-bit guard. A four-byte buffer whose byte 0 lacks the ASB pattern is rejected, not
    decoded. FromAutoStatusBack had no such check and would happily decode a DLE EOT / GS r reply
    into a status the printer never sent. (Note 0x12 β€” the DLE EOT fixed pattern this emulator
    emits β€” is exactly such a buffer.)
  • All four error bits. PrinterStatusEventArgs.IsInErrorState was the OR of byte-1 bits 6, 5, 3
    and 2 (recoverable, unrecoverable, autocutter, recoverable non-autocutter). The old browser decode
    read (b1 & 0x60) β€” bits 6 and 5 only. The emulator never sets 3 or 2, but a real printer does, so
    the mask is now 0x6C.

What is lost, stated rather than hidden

  • Three of the twelve parsed flags are not surfaced: paper currently feeding, waiting for
    online recovery
    , feed button pushed. Demonstrated unused β€” grep -rn for each across src/,
    tests/, samples/ and both heads (App.Browser, App.Desktop) returns the ESCPOS_NET
    declarations and nothing else. MonitorStatus has six fields and reads none of the three. The bits
    are still in the block StatusFrameReceived delivers, so a consumer that wants them can read them.
  • PaperLow while PaperOut. ESCPOS_NET read each paper pair with && and no masking, so a roll
    that is out reported IsPaperLow == true as well (this emulator sets both pairs in that state).
    The kept decode suppresses PaperLow when PaperOut β€” the pre-existing browser behaviour. This is
    unobservable through MonitorStatus: every consumer of PaperLow is already guarded by
    PaperOut (MonitorViewModel: s.PaperOut ? "Out" : s.PaperLow ? "Low" : "OK", and Ready reads
    only PaperOut).
  • GetStatus(), Status, PrinterName, Flush(…), Connected, Disconnected are not
    replaced. GetStatus() threw NotImplementedException upstream; Connected/Disconnected were
    only ever raised by the network printer's reconnect path, never for USB.
  • An invalid first block no longer fires an event. Before, it raised StatusChanged with an
    all-null PrinterStatusEventArgs, which == true turned into "Offline, no error" β€” a spurious
    offline flash. Now nothing is raised.

Two deliberate behaviour improvements

  • Send is synchronous and throws. BasePrinter.Write enqueued onto a 100 ms background pump
    whose body was catch (IOException) { } catch { } β€” a USB write failure was dropped on the floor.
    MonitorViewModel.Send already wraps SendAsync in a try/catch that logs, so a failure now
    reaches the Monitor log instead of vanishing. Job splitting at 15,000 bytes
    (BasePrinter._maxBytesPerWrite) is preserved, with one flush per job.
  • Status latency drops. BasePrinter consumed one byte per 100 ms, so a 4-byte block took ~400 ms
    to surface after arrival. StreamPrinter reads up to a packet at a time, so a block surfaces in one
    read cycle. UsbStream's read buffering is untouched (it is still correct, and its doc comment no
    longer refers to a type that is gone).

Tests

New project tests/CrossEscPos.Transports.Tests β€” 41 tests, no hardware. It references Core and
Transports only. Two red→green cycles, both observed:

Red Green
The port β€” stubbed Feed, Parse, and an unsplit Send Failed: 13, Passed: 20, Total: 33 Failed: 0, Passed: 33, Total: 33
The review fixes β€” the new defect tests against the pre-fix StreamPrinter test host crashed, plus Dispose_WaitsForAnInFlightSend… failed Failed: 0, Passed: 41, Total: 41

Neither red was a compile error. The port's sharpest one is the write splitting carried over from
BasePrinter:

Send_SplitsAJobLongerThanOneWrite
  Assert.Equal() Failure: Collections differ
  Expected: [15000, 15000, 1234]
  Actual:   [31234]

and the review fixes' red was not a failure but a process abort, which is the whole point of that
finding:

The active test run was aborted. Reason: Test host process crashed :
Unhandled exception. System.InvalidOperationException: handler blew up
   at StreamPrinter.<ReadStatusLoop>b__18_0(Byte[] frame) … StreamPrinter.cs:line 123
   at AutoStatusBackReader.Feed(…) … AutoStatusBackReader.cs:line 71
   at StreamPrinter.ReadStatusLoop() … StreamPrinter.cs:line 123
   at System.Threading.Thread.StartCallback()

Coverage, driven over a FakeTransport stream that records each write separately and serves the
status channel:

  • Sending β€” splitting a job longer than one write and reassembling it byte-for-byte, one flush
    per job, a short job written whole, an empty job writing nothing, Send(null), Send after
    Dispose, Send propagating a write failure (the headline behaviour change, and previously
    untested), and Send serialising two concurrent jobs without interleaving their chunks.
  • Status channel β€” one event per 4-byte block; a block split across reads reassembled (3 bytes
    raises nothing, the 4th completes it); the read loop surviving a throwing read; the channel
    surviving a throwing handler
    ; a send-only stream never being read from.
  • End to end β€” StatusByteBuilder.AutoStatusBack(state) pushed onto the wire, framed by the
    transport, decoded by the reader, asserted field by field. This is the whole path that used to run
    through BasePrinter.
  • Lifetime β€” Dispose disposing the stream, stopping the status reads (the read count stops
    advancing), being idempotent, waiting out an in-flight Send so nothing is written after
    teardown
    , and Name plus its fallback.
  • Decode β€” the 144-state round trip; rejection of non-block lengths (0, 1, 2, 3, 5, 8, each with
    a valid byte 0 so only the length can reject them) and of byte 0 without the fixed bits (0x00,
    0x11, 0x12, 0x90); each byte-0 bit including the inverted drawer bit; all four error bits
    individually; paired paper bits (a lone bit is not a reading); PaperOut winning over PaperLow;
    byte 3 ignored.
  • Framing β€” grouping, holding a partial block, and frames that outlive the next one (the reader
    reuses one buffer).

What is not covered, and cannot be without a device: libusb itself β€” UsbPrinter's constructor
and endpoint discovery (FindBulkEndpoints), UsbStream's native read/write and its
teardown-vs-in-flight-transfer lock, and EnsureNativeSearchPath. All of that is unchanged by this
PR except for moving the constructor body into a static OpenDevice factory (so the stream can be
built before the base constructor runs) and deleting the BinaryWriter/BinaryReader wrappers. The
UsbStream class itself is byte-identical apart from its doc comment. Also uncovered: the
DesktopMonitorClient rewiring, which has no test project of its own.

Full suite: 172 passed, 0 failed β€” 129 Core + 2 Controls + 41 Transports, up from 131.

What the adversarial review changed

A read-only review of the first commit found two defects worth the second commit, both reproduced
before being fixed:

  1. A throwing StatusFrameReceived handler killed the process. The handler ran outside the read
    loop's try, on a bare Thread β€” an unhandled exception on a managed thread. BasePrinter did
    not behave this way: its StatusChanged?.Invoke sat inside a catch-all, so a throwing
    subscriber was swallowed. That made this an unadmitted regression, and StreamPrinter is
    public packaged API, so it was a consumer's process at stake. Each invocation is now isolated.
  2. Dispose tore the stream down under an in-flight Send. _writeLock did not cover
    _stream.Dispose(), so a job already past the disposed check kept writing into a disposed
    stream. Dispose now flips the flag atomically first (a waiting Send bounces), then takes the
    write lock β€” bounded, so a wedged transport cannot wedge teardown β€” before disposing. Send
    re-checks under the lock.

Three more were real but smaller: the Join's comment claimed a guarantee it does not provide
(the token is only checked between reads, so a blocking read is still in flight at teardown β€” the
native safety for USB is UsbStream's own flag and lock, and the comment now says so); Dispose's
guard was a non-atomic read-then-write; and ConnectAsync had no await at all, so the now-real
USB write ran synchronously on the UI thread the Monitor awaits from β€” up to the 5 s bulk timeout,
where main's BasePrinter.Write was just an enqueue. That one is moved off the caller's thread.

Four claims of mine in docs/Packages.md did not survive and were corrected: PrinterName is
replaced (by Name, same value); the OverridableDispose row only ever concerned a StreamPrinter
subclass, since UsbPrinter is and was sealed; "used almost none of BasePrinter" undersold what
was replaced; and the IPrinterResponder line oversold a consistency that is really a direction
inversion (below). Stale "over ESC-POS-.NET" prose in four more places was swept, and App.Desktop
now declares its own ESCPOS_NET reference instead of relying on a transitive path that Transports
no longer carries.

One finding deliberately not acted on, for the owner to settle: IPrinterResponder is documented
as "a channel the printer can write bytes back to the host over", and ReceiptPrinter.RegisterResponder
consumes it as exactly that. StreamPrinter is the host side, so implementing it inverts the
interface's direction β€” a StreamPrinter could be registered as an emulator responder, where the
emulator's status replies would be written out to the device as a print job. The contracts differ too:
NetClient.Send logs and swallows as a best-effort reply channel, StreamPrinter.Send throws.
Nothing in the repo consumes StreamPrinter through the interface, so dropping it would break no call
site. It is kept because it was asked for explicitly; say the word and it comes off.

Two findings were checked and left as documented preconditions rather than code changes, because
BasePrinter had them identically and changing them would be a redesign: AutoStatusBackReader is
single-reader (not thread-safe), and Feed's grouping is positional, so a channel mixing
DLE EOT / GS r replies with ASB would desync permanently. Verified unreachable through the shipped
Monitor, which never sends those requests.

The review also independently re-derived and confirmed the parts worth confirming: Parse is
bit-exact against both StatusByteBuilder.AutoStatusBack and the decompiled TryUpdatePrinterStatus
(no bit, mask or polarity wrong; 0x6C is exactly the four Did* properties IsInErrorState ORs);
OpenDevice is leak-equivalent to the original constructor on every throw path and the static
initialiser still runs first; Disconnect() is still safe twice, before connect, and after a failed
connect, with no printer leaked on any path; and FromAutoStatusBack agrees with the old decode on
every byte sequence the emulator can emit, diverging only on real-hardware bytes where the new
behaviour matches both the Epson layout and BasePrinter.

The package has zero ImageSharp and zero ESCPOS_NET

The SixLabors.ImageSharp 2.1.13 pin existed only to lift ESCPOS_NET's transitive 2.1.3 (the comment
above it said so). No code in Transports used an ImageSharp API β€” verified: zero hits outside the
.csproj. With ESCPOS_NET gone the pin has nothing to lift, so both are removed.

Verified on the packed artefact, not on the project file:

$ dotnet pack src/CrossEscPos.Transports -c Release   # nuspec <dependencies>
  CrossEscPos.Core  1.3.2
  LibUsbDotNet      3.0.224
  System.IO.Ports   10.0.8

$ monodis --assemblyref lib/net10.0/CrossEscPos.Transports.dll   # 13 refs, none matching
  System.Runtime, CrossEscPos.Abstractions, System.Net.Primitives, CrossEscPos.Core,
  System.Net.Sockets, System.Collections, System.IO.Ports, System.Threading.Thread,
  LibUsbDotNet, System.ComponentModel.Primitives, System.Threading, System.Memory, System.Linq

And the project builds with the audit gate fully on (NuGetAuditMode=all,
TreatWarningsAsErrors=true, nothing suppressed):

$ dotnet build src/CrossEscPos.Transports/CrossEscPos.Transports.csproj -c Release
  3 projects, 0 errors, 0 warnings

Nothing here touches the licence gate, suppresses an advisory, or adds a key.

CI is red, on 20 pre-existing errors β€” proven not to be this PR

Current state: run 37745824647
on 97bd84b fails at Restore with 20 NU1902/NU1903 errors. Every one is
SixLabors.ImageSharp 3.1.12, reaching through CrossEscPos.Rendering.ImageSharp:

5 errors x CrossEscPos.Rendering.ImageSharp @ 3.1.12
5 errors x CrossEscPos.App              @ 3.1.12
5 errors x CrossEscPos.App.Desktop      @ 3.1.12
5 errors x CrossEscPos.App.Browser      @ 3.1.12
--------------------------------------------------
0 errors x CrossEscPos.Transports        <- this PR's subject

Why this is not mine, measured rather than asserted

The first commit's CI ran green at 07:23 β€” build, all 164 tests, and all six packages packed. The
same commit, re-run at 07:52 with byte-identical code, failed with these same 20 errors:

Run SHA Result
37743132123 (first attempt) cd0d18e green β€” 164 tests, 6 packages
37743132123 (re-run, same SHA, same code) cd0d18e red β€” the same 20
37745824647 97bd84b red β€” the same 20

So what changed between 07:23 and 07:52 was the runner's NuGet advisory feed catching up with the
Six Labors batch published 2026-10-07, not anything in this branch. NuGetAuditMode=all plus
TreatWarningsAsErrors=true (both in Directory.Build.props) turn those advisories into errors.

main has the same problem, worse β€” locally, with the gate untouched:

$ git checkout origin/main && dotnet build CrossEscPos.slnx -c Release
  25 Error(s)      # 5 GHSAs x 5 projects

$ # this branch
  20 Error(s)      # the 5 that CrossEscPos.Transports contributed are gone

main's last CI run was 2026-09-22, before the advisories existed, so its green badge is simply old.
The local figures and CI now agree exactly β€” 20 errors, the same four projects, nothing from
Transports.

It cannot be fixed here

The advisories' first patched release is 4.1.2; there is no patched 3.x. Clearing the remaining 20
means the ImageSharp 4 migration, which is
#25 β€” itself blocked on a Six Labors
licence only the owner can request. Doing it here would duplicate that PR and create exactly the
conflict this ordering is meant to avoid.

This PR strictly improves the number: 25 β†’ 20. Nothing in it touches the audit, the licence gate,
NoWarn, or any workflow.

What is nonetheless proven green

  • The one CI run that completed before the feed caught up exercised the whole tree on this code:
    Build succeeded, 164 passed / 0 failed across all three test projects, and all six packages
    packed including CrossEscPos.Transports.1.3.2.nupkg.
  • CrossEscPos.Transports builds with the audit gate fully on, nothing suppressed:
    $ dotnet build src/CrossEscPos.Transports/CrossEscPos.Transports.csproj -c Release
      3 projects, 0 errors, 0 warnings
    
  • The whole solution compiles clean once the pre-existing advisories are set aside β€” audit disabled
    locally only, never committed:
    $ dotnet build CrossEscPos.slnx -c Release -p:NuGetAudit=false
      17 projects, 0 errors, 0 warnings
    $ # all three test projects
      129 + 2 + 41 = 172 passed, 0 failed
    
  • tests/CrossEscPos.Transports.Tests needs none of that: it does not reference
    Rendering.ImageSharp, so it builds and runs clean with the gate on. That is also why the
    AutoStatusBackReader unit tests live there rather than in CrossEscPos.Core.Tests, which cannot
    currently be built at all β€” the test file says so, and says to move them once Move the ImageSharp backend to SixLabors.ImageSharp 4.1.2Β #25 lands.

Ordering against #25 β€” this one is meant to land first

#25 (fix/imagesharp-4) also edits
src/CrossEscPos.Transports/CrossEscPos.Transports.csproj, moving the same ImageSharp pin from
2.1.13 to 4.1.2. This PR deletes that pin and the ESCPOS_NET reference above it. The two
collide on the same lines.

#25 is blocked indefinitely on a Six Labors Community licence only the owner can request. This PR is
blocked on nothing. So:

On rebase, #25 should discard its CrossEscPos.Transports hunk entirely. Not merge it, not
reconcile the version β€” drop it. After this PR there is no ImageSharp reference in Transports to
bump, and #25's own "Also in scope, deliberately" section about Transports carrying a second copy
of the problem no longer applies: the second copy is gone, not upgraded. #25's
docs/Packages.md section will also need re-siting under the ## Breaking changes heading this PR
adds.

It removes one of the two licence-gate blockers

Worth stating precisely, because the obvious phrasing is wrong: no project trips the Six Labors
licence gate on main today.
ValidateLicenseTask ships only in SixLabors.ImageSharp 4.x and
SixLabors.ImageSharp.Drawing 3.x β€” verified by looking for a build/ folder in each restored
package:

Package build/…targets with ValidateLicenseTask
SixLabors.ImageSharp 2.1.3, 2.1.13 no build/ folder at all
SixLabors.ImageSharp 3.1.12 build/ has only a .props β€” no targets, no task
SixLabors.ImageSharp 4.1.2 yes
SixLabors.ImageSharp.Drawing 2.1.7 no build/ folder at all
SixLabors.ImageSharp.Drawing 3.1.2 yes

main is on 2.1.13 / 3.1.12 + Drawing 2.1.7, so the gate is not reached. "Two projects trip it" is
true of #25's tree, not of main.

Conditional on #25, the "two projects" part checks out, and #25's own CI run says so directly rather
than by inference β€” 37735754861
fails twice, once per project, from two different packages' targets:

sixlabors.imagesharp.drawing/3.1.2/build/SixLabors.ImageSharp.Drawing.targets(28,5): error :
  No Six Labors license found. ...  [src/CrossEscPos.Rendering.ImageSharp/...csproj]
sixlabors.imagesharp/4.1.2/build/SixLabors.ImageSharp.targets(28,5): error :
  No Six Labors license found. ...  [src/CrossEscPos.Transports/...csproj]

With this PR landed first, Transports has no ImageSharp at all, so the second of those two cannot
occur and #25 needs the key for Rendering.ImageSharp only β€” two blockers become one. One key
cleared both anyway, so this does not unblock #25; it narrows its blast radius and removes a project
from the licence surface permanently.

Breaking for consumers

UsbPrinter stops being a BasePrinter. Recorded for consumers in
docs/Packages.md under a new ## Breaking changes heading, in the same plain
register as the rest of that file: a was/is table for every member that moved, and the dropped flags
named individually.

The heading is new because the ## Dependency floors changed in 1.4.0 section referenced in the
brief does not exist on main β€” it is added by #25. No ticket or work item is invented.

<Version> is deliberately not bumped. This repository bumps it in its own commit (d7299e2 Bump version to 1.3.2), and #25 already edits Directory.Build.props to move the family to 1.4.0 β€”
touching it here would add a second conflict with #25 for no benefit. The docs entry states the
change without claiming a version.

docs/Architecture.md still listed ESC-POS-.NET as a Transports dependency; corrected.

Not touched

CrossEscPos.App keeps its own ESCPOS_NET reference (MonitorViewModel uses the EPSON emitter to
build test jobs), and DesktopMonitorClient still uses SerialPrinter / NetworkPrinter /
BasePrinter for the TCP and serial lanes. Those are out of scope: this PR removes the dependency
from the packaged library, where it sets a consumer's dependency floor, not from the app. The
consequence is that DesktopMonitorClient now bridges two unrelated printer types, which is what the
new private IPrinterLink seam is for β€” one implementation per status model, so the branching does
not spread through ConnectAsync, SendAsync and Disconnect.

One thing noticed and left alone: a new UsbPrinter(...) that throws (the common libusb-missing
case) escapes ConnectAsync before the try that would call AppendLibusbHelp(), so that help text
never shows for a connect failure β€” only for a device-list failure. Pre-existing, unrelated to this
change, and fixing it would alter behaviour nobody asked about.

UsbPrinter was the only transport deriving from ESCPOS_NET's BasePrinter, and
used almost none of it: it built its own BinaryWriter/BinaryReader over its own
UsbStream and overrode OverridableDispose. What BasePrinter did carry was the
stream pump (write splitting at 15,000 bytes, a background read loop) and the
parse of the 4-byte Automatic Status Back block into PrinterStatusEventArgs.

Both now live in this repository:

- StreamPrinter (Transports) is the host side of a printer conversation over
  any Stream β€” IPrinterResponder.Send out, raw ASB blocks back on
  StatusFrameReceived. UsbPrinter derives from it and supplies the UsbStream.
- AutoStatusBackReader (Core) frames and decodes the block, next to
  StatusByteBuilder.AutoStatusBack, whose exact inverse it is.

DesktopMonitorClient did consume the parsed status, so the behaviour is
preserved rather than dropped: its USB link decodes the raw block through
AutoStatusBackReader, which is the same decode the browser head already used
via MonitorStatus.FromAutoStatusBack. Two ESCPOS_NET decode details are kept
because a real printer can exercise them β€” rejecting a block whose first byte
lacks the ASB fixed bits, and folding all four byte-1 error bits into the error
flag. Three flags nothing reads (paper feeding, waiting for online recovery,
feed button pushed) are not surfaced; the bits are still in the delivered block.

With ESCPOS_NET gone, the SixLabors.ImageSharp 2.1.13 pin goes too β€” it existed
only to lift ESCPOS_NET's transitive 2.1.3 and no code here used ImageSharp.
CrossEscPos.Transports now builds with the NuGet audit fully on, clearing the
5 advisory findings it was contributing to the repository's 25.

Breaking for consumers holding a UsbPrinter; recorded in docs/Packages.md.
A throwing StatusFrameReceived handler killed the process. The handler ran
outside the read loop's try, on a bare thread, so a subscriber's exception was
an unhandled exception on a managed thread. Reproduced: the test host aborted
with "Unhandled exception ... at StreamPrinter.ReadStatusLoop". ESCPOS_NET's
BasePrinter did not behave this way β€” its StatusChanged invoke sat inside a
catch-all β€” so this was an unadmitted regression. Each invocation is now
isolated, with a backstop around the framing.

Dispose tore the stream down under an in-flight Send: _writeLock did not cover
_stream.Dispose(), so a job already past the disposed check kept writing into a
disposed stream. Dispose now flips the flag atomically first (so a Send waiting
on the lock bounces), and takes the write lock β€” bounded, so a wedged transport
cannot wedge teardown β€” before disposing the stream. Send re-checks under the
lock. The Interlocked guard also stops two racing Dispose calls both running
the teardown.

The join's comment claimed it prevented a read being in flight at teardown. It
does not: the token is only checked between reads. Corrected to state the real
precondition β€” the stream bounds its own reads, and the native safety for USB is
UsbStream's _closing flag and lock. Timeout cut 2 s -> 1 s, well clear of
UsbStream's 200 ms read timeout.

ConnectAsync did a synchronous USB bulk write on the UI thread: it had no await,
and the Monitor awaits it from the UI thread. On main that call was
BasePrinter.Write, an enqueue; it is now a real write that blocks up to the
5 s bulk timeout. Moved off the caller's thread.

Also: MaxBytesPerWrite is static readonly rather than const, so it is not baked
into consumers; documented that AutoStatusBackReader is single-reader and that
Feed's positional grouping assumes an ASB-only channel (BasePrinter had the same
property); documented that the status thread starts in the constructor.

docs/Packages.md corrections: PrinterName IS replaced, by Name, with the same
value; the OverridableDispose row only ever concerned a StreamPrinter subclass,
since UsbPrinter is and was sealed; "used almost none of BasePrinter" undersold
what was replaced (the pump, chunking, flush policy, read loop and framing, not
just a 4-byte parse); and the IPrinterResponder line now says plainly that
StreamPrinter is the host driving a printer while NetClient/SerialServer are the
printer answering a host.

Swept stale ESC-POS-.NET prose that is now wrong for USB (IMonitorClient,
IPlatformServices, StatusByteBuilder, docs/Using-the-App.md), and declared
App.Desktop's own ESCPOS_NET reference: it uses NetworkPrinter/SerialPrinter
directly and was relying on a transitive path that Transports no longer carries.

Tests 33 -> 41. New: a throwing handler does not stop the channel; Dispose waits
out an in-flight Send and nothing is written post-teardown; Send propagates a
write failure (the headline behaviour change, previously untested); Send
serialises concurrent jobs; Send(null); Name and its fallback. Tightened the
block-length rejection rows, which passed for the wrong reason β€” their byte 0
also failed the fixed-bit guard.

Red before, against the pre-fix StreamPrinter: test host crashed on the handler
test, Dispose_WaitsForAnInFlightSend failed. Green after: 41/41, and 172/172
across all three test projects.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant